<template>
  <a-card class="h-100">
    <template #title>
      <a-button @click="addMenu">添加菜单</a-button>
    </template>

    <a-table :columns="columns" :data-source="data" rowKey="id">
      <template #icon="{ record }">
        <span>
          {{record.icon}}
        </span>
      </template>
      <template #operation="{ record }">
        <span>
          <a-button size="small" @click="handleEdit(record)">编辑</a-button>
          &nbsp;
          <a-button size="small" type="danger" @click="handleDelete(record)">删除</a-button>
        </span>
      </template>
    </a-table>
  </a-card>
</template>
<script lang='ts'>
import { useRouter } from 'vue-router'
import { defineComponent, ref } from 'vue'
import { Modal, message } from 'ant-design-vue'
import { getAllMenus, deleteMenu } from '@/services/menu'

export default defineComponent({
  async setup () {
    const router = useRouter()
    // table 定义 columns
    const columns = [
      {
        dataIndex: 'number',
        key: 'number',
        title: '编号'
      },
      {
        title: '菜单名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '菜单级数',
        dataIndex: 'level',
        key: 'level'
      },
      {
        title: '前端图标',
        key: 'icon',
        dataIndex: 'icon',
        slots: {
          customRender: 'icon'
        }
      },
      {
        title: '排序',
        key: 'orderNum',
        dataIndex: 'orderNum'
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 200,
        align: 'center',
        slots: {
          customRender: 'operation'
        }
      }
    ]
    // table 数据源
    const data = ref([])
    const loadAllmenus = async () => {
      const { data: responseData } = await getAllMenus()
      data.value = responseData.data
    }
    await loadAllmenus()

    const addMenu = () => {
      router.push('/menu/add')
    }

    const handleEdit = (record: {id: number}) => {
      router.push({
        name: 'menu-edit',
        params: {
          id: record.id
        }
      })
    }

    const handleDelete = (record: {id: number}) => {
      Modal.confirm({
        title: 'Are you sure delete this menu?',
        okText: 'Yes',
        cancelText: 'No',
        async onOk () {
          try {
            const { data } = await deleteMenu(record.id)
            if (data.code === '000000') {
              loadAllmenus()
              message.success('删除成功')
            }
          } catch (error) {
            console.log(error)
          }
        }
      })
    }

    return {
      addMenu,
      data,
      columns,
      handleEdit,
      handleDelete
    }
  }
})
</script>
<style lang="scss" scoped>
</style>
